package com.finance.system.support.utils;

import com.finance.system.file.entity.PhysicalFile;
import com.finance.system.support.exception.FinanceBusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;

public class ResponseUtils {

    private final static Logger logger = LoggerFactory.getLogger(ResponseUtils.class);

    public static final String DOWNLOAD_CONTENT_DISPOSITION = "form-data; name=\"attachment\"; filename*=UTF-8''";
    public static void download(HttpServletResponse response, PhysicalFile file, String filename) {
        checkFile(file, filename);
        try (ServletOutputStream sos = response.getOutputStream()) {
            filename = URLEncoder.encode(filename, "UTF-8");

            response.setContentType(file.getFileSystem().getFileExtension());
            response.setHeader("Content-Disposition", DOWNLOAD_CONTENT_DISPOSITION + filename);
            response.setHeader("Content-Length", file.getFileSystem().getFileSize().toString());
            Files.copy(file.toPath(), sos);
        } catch (IOException e) {
            logger.error("download file has error. ");
        }
    }

    private static void checkFile(PhysicalFile file, String filename) {
        boolean exists = Files.exists(file.toPath());
        if(!exists){
            throw new FinanceBusinessException("file not exist");
        }
        if(StringUtils.isEmpty(filename.trim())){
            throw new FinanceBusinessException("file name should be confirmed");
        }

    }
}
